﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Utility;

namespace CookingPlan
{
    public class RecipeAnalysis
    {
        /// <summary>
        /// 菜谱文件XML文档内容
        /// </summary>
        public List<XmlDocument> RecipeFiles { get; set; }
        /// <summary>
        /// 时间和菜谱ID的二元组
        /// </summary>
        public List<TimeRecipeTuple> TimeRecipeTuple { get; set; }

        /// <summary>
        /// 初始化
        /// </summary>
        public RecipeAnalysis(IEnumerable<TimeRecipeTuple> recipeTuples)
        {
            RecipeFiles = new List<XmlDocument>();
            //消除重复路径
            List<string> paths = recipeTuples.Select(rt => rt.RecipeFile).Distinct().ToList();
            //分配菜谱ID
            TimeRecipeTuple = new List<TimeRecipeTuple>();
            foreach(var rt in recipeTuples)
            {
                TimeRecipeTuple.Add(new TimeRecipeTuple
                                        {
                                            Time = rt.Time,
                                            RecipeFile = paths.FindIndex(p => p == rt.RecipeFile).ToString()
                                        });
            }
            //加载菜谱
            foreach (string p in paths)
            {
                var recipeXml = new XmlDocument();
                recipeXml.Load(p);
                RecipeFiles.Add(recipeXml);
            }
        }

        /// <summary>
        /// 获取所有的食材及总量和度量
        /// </summary>
        /// <returns></returns>
        public List<Ingredient> GetAllIngredients()
        {
            var res = new List<Ingredient>();
            foreach (var t in TimeRecipeTuple)
            {
                var r = RecipeFiles[int.Parse(t.RecipeFile)];
                var ingredients = r.GetElementsByTagName("ingredients")[0].ChildNodes;//TODO 可能会引发空数组异常
                foreach(XmlElement i in ingredients)
                {
                    var ingredient = new Ingredient(i.GetAttribute("name"), double.Parse(i.GetAttribute("amount")),
                                                    i.GetAttribute("dimension") == "g" ? Dimension.g : Dimension.ml);
                    if(res.Exists(re=>re.Name == ingredient.Name))
                    {
                        int index = res.FindIndex(re => re.Name == ingredient.Name);
                        res[index].Amount += ingredient.Amount;
                    }
                    else
                    {
                        res.Add(ingredient);
                    }
                }
            }
            return res;
        }
    }
}
